import javax.naming.*
import javax.jms.*

/** Obtain a connection factory from JNDI and create a JMS session, then pass
    to user closure. */
def withJmsSession(closure) {
	def ctx = new InitialContext()
	try {
		def cf = ctx.lookup("ConnectionFactory") as ConnectionFactory
		//println("JNDI JMS ConnectionFactory found: ${cf}")
		def conn = cf.createConnection()
		try {
			def session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE)
			conn.start()
			closure.call(session)
			session.close()
		} finally {
			conn.close()
		}
	} finally {
		ctx.close()
	}
}


// groovy.bat drainQueue.groovy ExampleQueue
// WARNING: All message content will be lost!!!
def queueName = args[0]
def counter = 0
withJmsSession { session ->
	def queue = session.createQueue(queueName)
	def consumer = session.createConsumer(queue)
	def msg = null
	while ((msg = consumer.receive(3000)) != null) {
		println("Drained msg: ${msg}")
		counter++
	}
}
println("Total ${counter} msgs removed.")